<?php
/**
 * (logic) 中国发FBA（运单异常）
 */
namespace App\Logic\Delivery;

use App\Models\Amazon\FbaFulfillmentInventory;;
use App\Models\Delivery\FBADelivery;
use Illuminate\Support\Facades\DB;
class ExCheck
{
    public static function handle()
    {
        $date7 = date('Y-m-d 00:00:00',strtotime('-7 days'));
        $date20 = date('Y-m-d 00:00:00',strtotime('-20 days'));
        FBADelivery::query()
            ->where('ex_status',1)
            ->orderBy('id')
            ->chunk(100, function ($items) use ($date7,$date20){
                DB::beginTransaction();
                try{
                    foreach ($items as $item){
                        if($item->status < 6){
                            if($item->created_at < $date7){
                                $item->ex_status = 3;
                                $item->ex_desc = 2;
                                $item->save();
                            }
                        }else{
                            if($item->delivered_at < $date7){
                                $fulfillment = FbaFulfillmentInventory::query()
                                    ->where('fba_shipment_id',$item->delivery_no)
                                    ->count();
                                if($fulfillment == 0){
                                    $item->ex_status = 3;
                                    $item->ex_desc = 3;
                                    $item->save();
                                }else{
                                    $fulfillmentQuantity = FbaFulfillmentInventory::query()
                                        ->where('fba_shipment_id',$item->delivery_no)
                                        ->sum('quantity');
                                    if($item->ship_total_unit < $fulfillmentQuantity){
                                        if($item->delivered_at < $date20){
                                            $item->ex_status = 3;
                                            $item->ex_desc = 4;
                                            $item->save();
                                        }
                                    }else{
                                        $item->ex_status = 2;
                                        $item->ex_desc = 1;
                                        $item->save();
                                    }
                                }
                            }
                        }
                    }
                    DB::commit();
                }catch (\Exception $e){
                    DB::rollBack();
                    report($e);
                }
        });
    }
}
